package com.ziyun.pop.mall.module.login;

import com.alibaba.fastjson.JSONObject;
import com.service.common.model.UserInfo;
import com.service.ucenter.api.UserInfoService;
import com.service.ucenter.constant.UcenterResult;
import com.service.utils.push.umeng.JsonResult;
import com.utility.JsonUtils;
import com.utility.New;
import com.utility.StringUtils;
import com.utility.http.HttpUtils;
import com.ziyun.pop.mall.base.service.CorePlatformService;
import com.ziyun.pop.mall.base.utils.Base64Util;
import com.ziyun.pop.mall.module.register.model.RegisterVO;
import com.ziyun.pop.mall.module.register.service.RegisterService;
import com.ziyun.pop.mall.module.user.entity.SysUserEntity;
import com.ziyun.pop.mall.system.config.HttpRequestLocal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * pop用户登录/跳转后台
 * 
 * @Author:chenxiaoyi
 * @Date:2018/10/13 13:30
 */
@Controller
public class PopLoginController {

	private static Logger _log = LoggerFactory.getLogger(PopLoginController.class);

	@Value("${erp-api}")
	private String erpApi;

	@Autowired
	private UserInfoService userInfoService;

	@Autowired
	private RegisterService registerService;

	@Autowired
	private HttpRequestLocal httpRequestLocal;

	/**
	 * 到登录界面
	 * 
	 * @return
	 */
	@GetMapping("/login")
	public ModelAndView login(String msg) throws Exception {
		ModelAndView view = new ModelAndView("/login/login.html");
		String decode = StringUtils.EMPTY;
		if (StringUtils.isBlank(msg)) {
			decode = StringUtils.EMPTY;
		} else {
			decode = URLDecoder.decode(msg, "utf-8");
		}
		view.addObject("msg", decode);
		return view;
	}

	/**
	 * 用户登录
	 * 
	 * @param request
	 */
	@GetMapping("/login.do")
	public ModelAndView login(SysUserEntity entity, HttpServletRequest request, RedirectAttributes attr)
			throws Exception {
		ModelAndView view = new ModelAndView();
		Map<String, Object> params = new HashMap<>();
		Map<String, Object> paramHeaderMap = New.hashMap();
		params.put("userName", entity.getUsername());
		params.put("password", entity.getPassword());

		_log.info("--------skip to erp----------");

		// 远程调用
		String url = erpApi + "/port/sys/login";
		String response = HttpUtils.doPost(url, paramHeaderMap, JsonUtils.map2String(params));
		Map<String, Object> map = new HashMap<>();
		if (StringUtils.isNotBlank(response)) {
			map = JsonUtils.string2Map(response, String.class, Object.class);
		} else {
			map.put("code", 500);
			map.put("msg", "登录失败,请稍后再试");
		}

		if ((Integer) map.get("code") != 0) {
			String msg = URLEncoder.encode(map.get("msg").toString(), "utf-8");
			view.setViewName("redirect:/login?msg=" + msg);
		} else {
			Object o = map.get("popUserInfo");
			String s = JsonUtils.object2String(o);
			SysUserEntity popUserInfo = JsonUtils.string2Object(s, SysUserEntity.class);
			Long mallUserId = popUserInfo.getMallUserId();

			if (mallUserId == null || mallUserId.intValue() <= 0) {
				RegisterVO registerVO = new RegisterVO();
				registerVO.setSellerId(popUserInfo.getSellerId());
				registerVO.setSellerName(popUserInfo.getUsername());
				mallUserId = registerService.registerUserApi(registerVO);
				if (mallUserId.intValue() > 0) {
                    popUserInfo.setMallUserId(mallUserId);
                     HttpUtils.doPost( erpApi + "/port/sys/updateUser", paramHeaderMap, JsonUtils.object2String(popUserInfo));
				}
			}
			httpRequestLocal.setSessionValue("userId", mallUserId);
			httpRequestLocal.setSessionValue("popUserId", popUserInfo.getUserId());
			httpRequestLocal.setSessionValue("sellerId", popUserInfo.getSellerId());
			httpRequestLocal.setSessionValue(CorePlatformService.ACCESS_CURRENT_USER, popUserInfo.getMallUserId());
			httpRequestLocal.setSessionValue(CorePlatformService.ERP_PRIMARY_USERNAME, popUserInfo.getUsername());
			httpRequestLocal.setSessionValue(CorePlatformService.ERP_PRIMARY_PASSWORD, popUserInfo.getPasswordOld());
			httpRequestLocal.setSessionValue(CorePlatformService.ERP_PRIMARY_PASSWORD_OLD, entity.getPassword());

			UcenterResult<UserInfo> userInfo = userInfoService.loadUserInfoByPOP();
			// 保存POP用户信息
			if (null != userInfo.getData()) {
				httpRequestLocal.setSessionValue( String.valueOf(userInfo.getData().getUserId()), JsonUtils.object2String(userInfo.getData()));
			}
			// 判断是去后台页面首页还是回到当前页面
			String referer = (String) request.getSession().getAttribute("referer");

			if (null == referer) {
				view.setViewName("redirect:/backIndex.do");
			} else {
				attr.addFlashAttribute("code", 1);
				view.setViewName("redirect:" + referer);
			}
		}
		return view;
	}

	/**
	 * 远程调用 跳转后台
	 * 
	 * @return
	 */
	@GetMapping("/backIndex.do")
	public void index(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<String, Object> params = new HashMap<>();
		String account = (String) request.getSession().getAttribute(CorePlatformService.ERP_PRIMARY_USERNAME);
		//String password = (String) request.getSession().getAttribute(CorePlatformService.ERP_PRIMARY_PASSWORD);
		String passwordold = (String) request.getSession().getAttribute(CorePlatformService.ERP_PRIMARY_PASSWORD_OLD);
//		params.put("userName", account);
//		params.put("password", passwordold);
		_log.info("--------login to erpBackStage----------");
		try {
			StringBuffer url = new StringBuffer(erpApi + "/port/sys/jumpBackstage");

			url.append("?token=");
			JSONObject json = new JSONObject();
			json.put("userName", account);
			json.put("password", passwordold);

			String jsonStr = URLEncoder.encode(json.toJSONString(), "UTF-8");
			url.append(stringToBase64(jsonStr));
			response.sendRedirect(url.toString());
		} catch (Exception e) {
			_log.error("--------login to erpBackStage error (Catch Exception redirect /login)----------");
			response.sendRedirect("/login");
		}
	}

	/**
	 * 跳转商城首页
	 * 
	 * @param request
	 * @param response
	 */
	@GetMapping("/toMallIndex.do")
	public ModelAndView jumpMallIndex(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String path = "";
		try {
			String data = request.getParameter("token");
			String re = base64ToString(data);
			re = URLDecoder.decode(re, "UTF-8");
			Map<String, String> dataMap = JsonUtils.string2Map(re, String.class, String.class);
			String s = dataMap.get("popUserInfo");
			path =  StringUtils.isBlank(dataMap.get("path"))?"/index.do":dataMap.get("path") ;
			SysUserEntity popUserInfo = JsonUtils.string2Object(s, SysUserEntity.class);
			httpRequestLocal.setSessionValue("userId", popUserInfo.getMallUserId());
			httpRequestLocal.setSessionValue("sellerId", popUserInfo.getSellerId());
			httpRequestLocal.setSessionValue("popUserId", popUserInfo.getUserId());
			httpRequestLocal.setSessionValue(CorePlatformService.ACCESS_CURRENT_USER, popUserInfo.getMallUserId());
			httpRequestLocal.setSessionValue(CorePlatformService.ERP_PRIMARY_USERNAME, popUserInfo.getUsername());
			httpRequestLocal.setSessionValue(CorePlatformService.ERP_PRIMARY_PASSWORD, popUserInfo.getPasswordOld());
			httpRequestLocal.setSessionValue(CorePlatformService.ERP_PRIMARY_PASSWORD_OLD, popUserInfo.getPasswordOld());

			 UcenterResult<UserInfo> userInfo = userInfoService.loadUserInfoByPOP();
			// 保存POP用户信息
			if (null != userInfo.getData()) {
				httpRequestLocal.setSessionValue(String.valueOf(userInfo.getData().getUserId()),
						JsonUtils.object2String(userInfo.getData()));
			}
		} catch (Exception e) {
			_log.error("-------------pop skip mall error---------------");
		} finally {

			return new ModelAndView("redirect:"+path);
		}
	}

	/**
	 * erp后台退出后 pop清除
	 */
	@GetMapping("/exitSystem")
	public ModelAndView exitSystem() {
		return new ModelAndView("/login/logout.html");
	}

	/**
	 * pop退出
	 * @param request
	 * @return
	 */
	@PostMapping("/logout")
	@ResponseBody
	public JsonResult logout(HttpServletRequest request){
		request.getSession().invalidate();
		httpRequestLocal.getSession().invalidate();
		return JsonResult.success(erpApi+"/login.html");
	}


	/**
	 * popMall商城退出，后台也同时退出
	 * @param response
	 * @return
	 */
	@GetMapping("/mallLogout")
	public void mallLogout(HttpServletResponse response) throws Exception {
		httpRequestLocal.getSession().invalidate();
		response.sendRedirect(erpApi+"/port/sys/logOutAdmin");
	}


	/**
	 * 把String的转换成base64码
	 */
	private static String stringToBase64(String ss) {
		byte[] bytes = ss.getBytes();
		return  Base64Util.encode(bytes);
	}

	/**
	 * 把base64的String码转换成正常显示的字符串
	 */
	private static String base64ToString(String base64) {
		byte[] decode = Base64Util.decode(base64);
		return new String(decode);
	}
}
